#!/usr/bin/env python
# @Time: 2021/3/30 10:13
# @Author: CLK
# @SoftWare: PyCharm

"""
批量修改文件名称
"""

from os import path, listdir, rename, system

folder_path = input('请输入要改名的文件路径：')
new_name_index = 1
prefix = ''
if folder_path is not None and path.exists(folder_path):

    prefix_flag = input('是否使用前缀(例如：test_1)(y/n): ')
    if prefix_flag == 'y' or prefix_flag == 'Y' or prefix_flag == '是':
        prefix = input('请输入前缀：') + '-'

    mode = input('是否使用默认模式改名（默认模式：文件名从1开始）(y/n): ')
    if mode == 'n' or mode == 'N' or mode == "否":
        new_name_index = int(input('请输入起始文件名（数字）： '))

    # 获取路径下所有的文件
    file_name = listdir(folder_path)

    if len(file_name) > 0:
        file_type = None
        for name in file_name:
            old_file = path.join(folder_path, name)
            if path.isdir(old_file):
                continue
            if file_type is None:
                file_type = path.splitext(name)[1]
            new_file = path.join(folder_path, prefix + str(new_name_index) + file_type)
            try:
                rename(old_file, new_file)
            except FileExistsError:
                new_file = path.join(folder_path, prefix + str(new_name_index) + 'tmp_file' + file_type)
                rename(old_file, new_file)
            new_name_index += 1

        # 改名完成后，把t去掉
        file_name = listdir(folder_path)
        for name in file_name:
            if name.find('tmp_file') != -1:
                old_file = path.join(folder_path, name)
                new_file = path.join(folder_path, name.replace('tmp_file', ''))
                rename(old_file, new_file)

    else:
        print('该路径下没有文件：', folder_path, '\n')
        system("pause")
else:
    print('路径错误或路径不存在！！！\n')
    system("pause")
